<template>
    <div class="popProjectFilling-box">
        <el-dialog title="选择服务参与活动" :visible.sync="popProjectFilling_Show" width="800px" top="6vh">
            <div class="popProjectFilling-div" v-if="isShowGoods">
                <div class="cascader-div">
                    <el-cascader size="mini" v-model="searchform.catid" :options="cat_ls" class="sele-w"
                        style="width: 200px;" :props="propsdata" @change="changeList" :show-all-levels="false"
                        :collapse-tags="true" placeholder="请选择分类" clearable filterable
                        @visible-change="handleCascaderVisibleChange">
                    </el-cascader>
                </div>
                <LoadList :containerHeight="560" :loading="lLoading" :noMore="lNoMore" @load-more="loadFun">
                    <template v-if="goods_ls && goods_ls.length">
                        <div class="list-item" v-for="(item, index) in goods_ls" :key="index"
                            @click.stop="selectFun(item)">
                            <div class="list-img">
                                <img :src="item.imgs || 'https://cdn.imiyun.com/static/yd/imgs/g-default.png'" alt="">
                            </div>
                            <div class="lsit-div">
                                <p class="">
                                    <span class="bold"> {{ item.title }} </span>
                                    <span class="font_size12">（{{ item.type_title }}）</span>
                                </p>
                                <p>{{ item.gd_brand }}</p>
                                <p class="mony">{{ item.price }}</p>
                            </div>
                        </div>
                    </template>
                    <el-empty v-else description="暂无数据"></el-empty>
                </LoadList>
            </div>
            <div class="list-item-info" v-else>
                <div class="list-item-info-box">
                    <div class="list-item-info-div">
                        <img :src="selectObj.imgs || 'https://cdn.imiyun.com/static/yd/imgs/g-default.png'" alt="">
                    </div>
                    <div class="list-item-info-pric">
                        <p>{{ goodsDetail.title }}</p>
                        <p>{{ goodsDetail.gd_brand }}</p>
                        <p class="price">{{ goodsDetail.price }}</p>
                    </div>
                </div>
                <div class="infoSetBox">
                    <div class="infoSetDiv">
                        <div class="left-box flex_row">
                            <div class="left-box-item" v-if="gd_price && gd_price.length > 0">
                                <el-dropdown trigger="click" placement="bottom-start" @command="psortChange"
                                    style="cursor: pointer;">
                                    <span class="title-pic ac-select mr5">
                                        {{gd_price.find(item => item.psort == psort).title || '默认' }}
                                        <i class="el-icon-arrow-down ml5"></i>
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item :command="item.psort" v-for="(item, index) in gd_price"
                                            :key="index">
                                            {{ item.title }}
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                            <el-input-number class="input-wp" v-model="query.price" size="small" :min="0"
                                :precision="2"></el-input-number>
                            <span class="ml5">{{ goodsDetail.unit_title }}</span>
                        </div>
                        <div class="left-box flex_row">
                            <span class="mr10"> 折 扣 </span>
                            <el-input-number class="input-wp" v-model="discountNum" size="small" :min="0"
                                :precision="2" :max="100"></el-input-number>
                            <span class="ml5">%</span>
                        </div>
                    </div>
                    <div class="infoSetDiv">
                        <div class="left-box flex_row">
                            <div class="left-box-item" v-if="goodsDetail.cost_ls && goodsDetail.cost_ls.length > 0">
                                <el-dropdown trigger="click" placement="bottom-start" @command="costChange"
                                    style="cursor: pointer;">
                                    <span class="title-pic ac-select mr5">
                                        {{goodsDetail.cost_ls.find(item => item.id == costi).title}} <i
                                            class="el-icon-arrow-down ml5"></i>
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item :command="item.id"
                                            v-for="(item, index) in goodsDetail.cost_ls" :key="index">
                                            {{ item.title }}
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                            <el-input-number class="input-wp" v-model="costPrice" size="small" :precision="2"
                                :min="1"></el-input-number>
                            <span class="ml5">{{ goodsDetail.unit_title }}</span>
                        </div>
                        <div class="left-box flex_row">
                            <span class="mr10"> 数 量 </span>
                            <el-input-number class="input-wp" v-model="query.number" size="small"
                                :min="1"></el-input-number>
                            <span class="ml5">{{ goodsDetail.unit_title }}</span>
                        </div>
                    </div>

                    <div class="infoSetDiv">
                        <div v-if="goodsDetail.outday_i" class="flex_row">
                            <div class="left-box-item">
                                <span>有效期</span>
                            </div>
                            <el-select class="input-wp" v-model="goodsDetail.outday_i" placeholder="请选择" size="small">
                                <el-option v-for="item in goodsDetail.outday_ls" :key="item.id" :label="item.title"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </div>
                    </div>

                    <div class="infoSetDiv flex_row" style="align-items: flex-start;">
                        <span style="margin-right: 10px;">备注</span>
                        <el-input type="textarea" size="small" :rows="2" style="width: 90%;" maxlength="200"
                            placeholder="请输入备注信息（200字内）" v-model="query.txt">
                        </el-input>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer" v-if="!isShowGoods">
                <div class="footer-summary-box">
                    <div class="footer-info">
                        <div class="footer-item">
                            <span class="footer-label">商品名称</span>
                            <span class="footer-value">{{ goodsDetail.title }} </span>
                        </div>
                        <div class="footer-divider"></div>
                        <div class="footer-item">
                            <span class="footer-label">数量</span>
                            <span class="footer-value">{{ query.number }} </span>
                        </div>
                        <div class="footer-divider"></div>
                        <div class="footer-item">
                            <span class="footer-label">总价</span>
                            <span class="footer-price">￥{{ (query.price * query.number * discountNum / 100).toFixed(2) }}</span>
                        </div>
                    </div>
                    <div class="footer-actions">
                        <el-button @click="BackFun" class="cancel-btn">取 消</el-button>
                        <el-button type="primary" @click="affirmFun" class="confirm-btn">确 定</el-button>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted,defineEmits } from '@vue/composition-api'
import LoadList from "@/components/commV2/LoadList/index.vue"
import config from "@/js/conf/Config.js";
const { proxy } = getCurrentInstance()
// 响应式数据
const searchform = ref({
    catid: "",
})
const cat_ls = ref([])
const popProjectFilling_Show = ref(false)
const propsdata = reactive({
    children: "ls",
    label: "title",
    value: "id",
    expandTrigger: "hover",
    checkStrictly: true,
})

const goods_ls = ref([])
const isShowGoods = ref(true)
const gd_price = ref([])
const psort = ref("1")
const goodsDetail = ref({}) // 服务信息
const price_ls = ref([])
const costi = ref("1") // 备注
const discountNum = ref(100) // 折扣
const costPrice = ref(0) // 价格
const selectObj = ref({})

const query = ref({
    gdid: 0, 
    unitid: '', 
    specid: '', 
    spec_dir: "1,2", 
    number: 1, 
    price: 0, 
    pricec: 0, 
    money_q: 0, 
    txt: ""
})


const pfrom = ref(0)
const maxPnum = 20
const lLoading = ref(false)
const lNoMore = ref(false)
const loadFun = () => {
    if (lNoMore.value) return
    pfrom.value += 20
    goods_list()
}

const emit = defineEmits(['determineFun'])

// 方法
const initData = () => {
    pfrom.value = 0
    lNoMore.value = false
    goods_ls.value = []
    query.value.price = 0
    query.value.number = 1
    query.value.txt = ''
    costPrice.value = 0
    discountNum.value = 100
    goodsDetail.value = {}
    isShowGoods.value = true
    goods_list()
}

const psortChange = (item) => { // 选择售价
    psort.value = item
    price_ls.value.forEach(row => {
        if (row.price_i == item) {
            query.value.price = Number(row.price) * discountNum.value / 100
            query.value.pricec = Number(row.price)
        }
    })
}

const costChange = (item) => {
    costi.value = item
    goodsDetail.value.cost_ls.forEach(row => {
        if (row.id == item) {
            costPrice.value = Number(row.price_txt)
        }
    })
}

const changeList = () => {
    // 处理分类变化
    initData()
}

const handleCascaderVisibleChange = (visible) => {
    // 处理联级选择器显示状态变化
    if (!visible) {
        // 当弹窗关闭时，确保状态正确
        console.log('联级选择器已关闭')
        // 可以在这里添加一些清理逻辑
    }
}

const affirmFun = () => { // 确认服务
    let chooseQuery= {
        ...query.value,
        img: goodsDetail.value.imgs,
        gdid: goodsDetail.value.id,
        unitid: goodsDetail.value.unit,
        specid: goodsDetail.value.catid,
        gdname: goodsDetail.value.title,
        spec_title: goodsDetail.value.doc,
        unit_title: goodsDetail.value.unit_title,
    }
    if(Number(query.value.number) < 1){
        proxy.$message.error('请输入数量')
        return      
    }
    emit('determineFun', chooseQuery)
    popProjectFilling_Show.value = false
}

const BackFun = () => { // 返回上一页
    query.value.price = 0
    costPrice.value = 0
    goodsDetail.value = {}
    isShowGoods.value = true
}

const order_gd_price = async () => {
    let param = {
        cpid: selectObj.value.cpid,
        gdid: selectObj.value.id,
        type_od: "",
        customerid: "",
    }
    let res = await proxy.$api({ url: config.YY_ORDER_GD_PRICE, data: param })
    if (res.status == 1) {
        gd_price.value = res.data.gd_price
        price_ls.value = res.data.price_ls
        query.value.pricec = Number(res.data.price_ls[0].pricec)
        psortChange(1)
    }
}

const goodsinfo_goods_detail = async () => { // 获取产品信息
    let param = {
        cpid: selectObj.value.cpid,
        gdid: selectObj.value.id,
    }
    let res = await proxy.$api({ url: config.YY_GOODSINFO_GOODS_DETAIL, data: param })
    goodsDetail.value = res.data.gd_info // 获取产品信息
    goodsDetail.value.cost_ls = goodsDetail.value.cost_ls.filter(item => {
        if (item.status == 1) return item
    })
    costChange(1)
}

// const cat_ls_ajax = async () => {
//     let res = await proxy.$api({ url: config.PROPRE_CAT_LS, data: {} })
//     cat_ls.value = res.data.catlist
// }

const goods_list = async () => {
    lLoading.value = true
    let params = {
        is_stock: 1, // 是否有货 1 是2否 
        pfrom: pfrom.value,
        pnum: maxPnum,
        catid: searchform.value?.catid ? searchform.value?.catid?.join(',') : '',
    }
    let res = await proxy.$api({ url: config.YY_GOODSINFO_GOODS_LIST, data: params })
    if (res.status == 1) {
        goods_ls.value.push(...res.data.goods_ls)
        cat_ls.value = res.data.cat_ls
        lLoading.value = false
        if (res.data?.goods_ls && res.data?.goods_ls.length < maxPnum) {
            lNoMore.value = true
        } else {
            lNoMore.value = false
        }
    } else {
        lNoMore.value = true
        lLoading.value = false
    }
}

const selectFun = (item) => {
    isShowGoods.value = false
    console.log("item====", item)
    selectObj.value = JSON.parse(JSON.stringify(item))
    goodsinfo_goods_detail()
    order_gd_price()
}


// 生命周期
onMounted(() => { })

// 暴露给父组件的方法
defineExpose({
    initData,
    popProjectFilling_Show,
    selectFun,
    affirmFun,
    BackFun
})
</script>

<style lang="scss" scoped>
.infoSetBox {
    .infoSetDiv {
        display: flex;
        margin-bottom: 20px;
    }
}

.left-box {
    width: 400px;
}

.popProjectFilling-box {
    width: 100%;

    .cascader-div {
        margin-bottom: 10px;
        height: 30px;
    }

    .list-item {
        width: 100%;
        display: flex;
        margin-bottom: 10px;
        border-bottom: 1px #f2f2f2 solid;
        padding-bottom: 10px;
        cursor: pointer;

        .list-img {
            width: 80px;
            height: 80px;
            display: block;
            overflow: hidden;
            border-radius: 5px;
            margin-right: 10px;
        }

        .lsit-div {
            width: 70%;

            p {
                height: 24px;
                line-height: 24px;
            }

            .mony {
                color: #fa4848;
            }
        }

        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }

    .popProjectFilling-div {
        width: 100%;
        height: 580px;
        overflow: auto;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .list-item-info {
        .list-item-info-box {
            padding: 10px;
            background-color: #f2f2f2;
            display: flex;
            margin-bottom: 20px;
            border-radius: 6px;

            .list-item-info-div {
                img {
                    width: 80px;
                    height: 80px;
                    display: block;
                    border-radius: 6px;
                    margin-right: 10px;
                }
            }

            .list-item-info-pric {
                .price {
                    margin-top: 20px;
                    color: red;
                }
            }
        }
    }
}

::v-deep .el-dialog__body {
    padding: 10px 20px;
}

::v-deep .el-input-number {
    padding-left: 0 !important;
    padding-right: 0 !important;
    width: 150px !important;

    .el-input__inner {
        padding-left: 0 !important;
        padding-right: 0 !important;
    }
}

::v-deep .el-cascader {
    width: 100%;

    .el-cascader__label {
        line-height: 28px;
    }

    .el-input__inner {
        height: 28px;
        line-height: 28px;
    }
}

::v-deep .el-cascader__dropdown {
    z-index: 3000 !important;
}

.input-wp {
    width: 200px !important;
}

.left-box-item {
    width: 80px;
}
.dialog-footer{
    padding: 0 20px;
}
/* Footer样式 - 参考chiceSku index.vue的bottom样式 */
.footer-summary-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 6px 14px;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    margin: 0 -20px -10px;
}

.footer-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.footer-item {
    display: flex;
    align-items: center;
    gap: 6px;
}

.footer-label {
    font-size: 14px;
    color: #64748b;
    font-weight: 500;
}

.footer-value {
    font-size: 14px;
    font-weight: 600;
    color: #0f172a;
    max-width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.footer-price {
    font-size: 16px;
    font-weight: 700;
    color: #e11d48;
    text-shadow: 0 1px 2px rgba(225, 29, 72, 0.1);
}

.footer-divider {
    width: 1px;
    height: 20px;
    background-color: #cbd5e1;
    margin: 0 16px;
}

.footer-actions {
    display: flex;
    gap: 12px;
}

.cancel-btn, .confirm-btn {
    min-width: 80px;
}
</style>